package com.drcoffee.drcoffeemall.util;

import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;

public class RSAUtil {

    //公钥，可以写前端
    public static String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFGQCndZbgwvGJ8vp0mv4CLo7BKAvh9LVz9oLH0LdRDNksYY8vuO3NThwf4Wln821uLwIicqFRElHcdfRcPUw+3vIjHa0ka0h6H86gzDqIYldQ+9WP9UIOgtsFyb5rnLh3oH1Syt0Ohrz5S4WqHClrSifoE9L5X/EXjIjQawFRCwIDAQAB";

    //私钥，只能放后端
    public static String private_key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIUZAKd1luDC8Yny+nSa/gIujsEoC+H0tXP2gsfQt1EM2Sxhjy+47c1OHB/haWfzbW4vAiJyoVESUdx19Fw9TD7e8iMdrSRrSHofzqDMOohiV1D71Y/1Qg6C2wXJvmucuHegfVLK3Q6GvPlLhaocKWtKJ+gT0vlf8ReMiNBrAVELAgMBAAECgYAIcDRdaZQePd3IbDI60FTIWKFOV7ahJb2XU4qpFm944QKn0KueT/ArswcPcmAXahSHBs3w1ympFStBeez7KBu8TP+Klqph7ycAOVjMpAL8M1Z9gf9KkWjGzetegl94fe87U6b2kLY+s3mjlFr66avdRaDQnDdyTBqYRGSGDpunCQJBAJ36euwAB0eea9aMX2UUPZl5waF0DnjSGTC/TXKE4hw1IysvsHmTzgGhyEpSwqeQxNkw22nNPcrpmr7o5xrimDUCQQDXrmzZM9LNOdYS+gvfkECpB+W0KaZpEdzhGakToxZyTCutiaGZI1W7Xar/cHBBt9RftUtSd68qA9Ra+gXU2ew/AkAUTIwg6PwGete2cMENNuWXY+q6eTQm2DA+cEZeUa7QGw/Sy8TsSk6tLQGUcz/p0hNJKRr4ZFPtT8j/gOO5M6aFAkEAmF22s7KypxzGqN1Qaf1kUIUttxr9Xpip67PPB/pcrx40dQIX0TFvLVA8rvvlseeF9p8CuR2n9wyBhku+tuHEzQJASKuooRQIebEQ1zboije17oXCu1rLuKi7xDtzTx7m02Z39ubxDjG5n6+KQqYCAlGKCd4HuzNd2qq9Fks3V3G1Ew==";

/*
    public static void main(String[] args) {
        //解密数据
        try {
            //生成公钥和私钥
            genKeyPair();
            String publicKey = keyMap.get(0);
            //打印出来自己记录下
            System.out.println("公钥:" + publicKey);
            String privateKey = keyMap.get(1);
            //打印出来自己记录下
            System.out.println("私钥:" + privateKey);

            //获取到后，可以放这里，测试下能不能正确加解密
            publicKey = public_key;
            privateKey = private_key;

            String orgData = "test";
            System.out.println("原数据：" + orgData);

            //加密
            String encryptStr =encrypt(orgData,publicKey);
            System.out.println("加密结果：" + encryptStr);

            //解密
            String decryptStr = decrypt(encryptStr,privateKey);
            System.out.println("解密结果：" + decryptStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/

    /**
     * RSA公钥加密
     *
     * @param str 加密字符串
     * @return 密文
     * @throws GeneralSecurityException 加密过程中的异常信息
     */
    public static String encrypt(String str) throws GeneralSecurityException {
        byte[] publicKeyBytes = Base64.getDecoder().decode(public_key.getBytes(StandardCharsets.UTF_8));
        PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedBytes = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * RSA私钥解密
     *
     * @param str 加密字符串
     * @return 明文
     * @throws GeneralSecurityException 解密过程中的异常信息
     */
    public static String decrypt(String str) throws GeneralSecurityException {
        byte[] privateKeyBytes = Base64.getDecoder().decode(private_key.getBytes(StandardCharsets.UTF_8));
        PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 编码返回字符串
     *
     * @param key 密钥
     * @return 编码后的字符串
     * @throws Exception 异常
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return Base64.getEncoder().encodeToString(key);
    }

    /**
     * 解码返回byte数组
     *
     * @param key 编码后的字符串
     * @return 解码后的byte数组
     * @throws Exception 异常
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return Base64.getDecoder().decode(key);
    }

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 1024;
    /**
     * 用于封装随机产生的公钥与私钥
     */
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();

    /**
     * 随机生成密钥对
     *
     * @throws Exception 异常
     */
    public static void genKeyPair() throws Exception {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString = encryptBASE64(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = encryptBASE64(privateKey.getEncoded());
        // 将公钥和私钥保存到Map
        // 0表示公钥
        keyMap.put(0, publicKeyString);
        // 1表示私钥
        keyMap.put(1, privateKeyString);
    }
}
